<?php
/**
 * User: ht
 * Date: 2019/8/14
 * Time: 10:19
 */

namespace backend\controllers;

use backend\models\Menu;
use backend\models\Module;
use backend\models\Role;
use backend\models\Route;
use backend\models\User;
use yii\helpers\Url;
use yii\web\Controller;
use Yii;

class IndexController extends BaseController
{

    public function actionIndex()
    {
        $menu = $this->getMenu();
        return $this->render('index', compact('menu'));
    }

    public function actionConsole()
    {
        return $this->render('console');
    }

    public function actionHome()
    {
        $type = input('type') ?: '1';
        $view = $type == 1 ? 'home' : 'home2';
        return $this->render($view);
    }

    public function getMenu()
    {
        $user = User::findOne(Yii::$app->user->id);
        $menu = Yii::$app->cache->get('menu' . $user->role_id);
        if ($menu) return $menu;
        $model = new Module();
        $menuIds = $model->getMenuIds();//菜单id
        $menuArr = Menu::find()->where(['in', 'id', $menuIds])->asArray()->all();
        $moduleIds = array_unique(array_column($menuArr, 'module_id'));
        $module = Module::find()->alias('a')->joinWith('menu')
            ->andWhere(['in', 'a.id', $moduleIds])
            ->andWhere(['a.is_show' => 1])
            ->orderBy('a.sort desc')
            ->asArray()->all();
        $role = Role::findOne($user->role_id);
        $jurisdiction = json_decode($role->jurisdiction);
        foreach ($module as &$list) {
            foreach ($list['menu'] as &$item) {
                $item['rule'] = Route::find()->where(['menu_id' => $item['id']])
                    ->andWhere(['is_show' => 1])
                    ->andWhere(['in', 'id', $jurisdiction])
                    ->asArray()->all();
            }
        }
        Yii::$app->cache->set('menu' . $user->role_id, $module);
        return $module;
    }

    /**
     * 清除缓存
     */
    public function actionClearCache()
    {
        $cache = Yii::$app->cache;
        if ($cache->flush()) {
            $this->json(200, '清除成功');
        }
        $this->json(100, '清除失败');
    }

    public function actionUser()
    {
        if (Yii::$app->request->isPost) {
            $id = input('id');
            $password = input('password');
            if (empty($password)) {
                $this->json(100, '请填写密码');
            }
            $model = User::findOne($id);
            $model->password = Yii::$app->security->generatePasswordHash($password);
            if ($model->save()) {
                $this->json(200, '修改成功');
            }
            $this->json(200, '修改失败');
        }
        $user = User::findOne(Yii::$app->user->id);
        return $this->render('userInfo', compact('user'));
    }
}
